import dayjs from "dayjs";
import { zxcvbn } from "@zxcvbn-ts/core";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { getKeyList, isAllEmpty, deviceDetection } from "@pureadmin/utils";
import {
  getUserList,
  addUser,
  upUser,
  delUser,
  resetPwd,
  doChangeScore
} from "@/api/system/user";
import { getRoleList } from "@/api/system/role";

import { ElForm, ElInput, ElFormItem, ElProgress } from "element-plus";
import AddUpTeacher from "@/components/common/AddUpTeacher";
import EditScore from "../form/index.vue";
import {
  type Ref,
  h,
  ref,
  toRaw,
  computed,
  reactive,
  onMounted,
  watch
} from "vue";

export function useUser(tableRef: Ref) {
  const form = reactive({
    name: "",
    number: "",
    pageNum: 1,
    pageSize: 10
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const allUserList = ref([]);
  const loading = ref(true);
  const treeData = ref([]);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "姓名",
      prop: "name",
      fixed: "left",
      minWidth: 120
    },
    {
      label: "工号",
      prop: "number",
      minWidth: 100
    },
    {
      label: "所属学院",
      prop: "college",
      minWidth: 120
    },
    {
      label: "所属系",
      prop: "collegeSystem",
      minWidth: 120
    },
    {
      label: "手机号",
      prop: "phone",
      minWidth: 100
    },
    {
      label: "电子邮箱",
      prop: "email",
      minWidth: 100
    },
    {
      label: "性别",
      prop: "sex",
      minWidth: 100,
      formatter: ({ sex }) => (sex == 1 ? "男" : "女")
    },
    {
      label: "民族",
      prop: "nationality",
      minWidth: 100
    },
    {
      label: "出生年月",
      prop: "birthday",
      minWidth: 100,
      formatter: ({ birthday }) =>
        birthday ? dayjs(birthday).format("YYYY-MM-DD") : ""
    },
    {
      label: "积分",
      prop: "score",
      minWidth: 100
    },
    {
      label: "学位",
      prop: "degree",
      minWidth: 100
    },
    {
      label: "学历",
      prop: "background",
      minWidth: 100
    },
    {
      label: "职称",
      prop: "titleNameList",
      minWidth: 100
    },
    {
      label: "职务",
      prop: "position",
      minWidth: 100
    },
    {
      label: "研究方向",
      prop: "direction",
      minWidth: 100
    },
    {
      label: "人员构成",
      prop: "bizType",
      minWidth: 100,
      formatter: ({ bizType }) => (bizType == 1 ? "校内人员" : "校外人员")
    },
    {
      label: "操作",
      fixed: "right",
      width: 220,
      slot: "operation"
    }
  ];

  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  // 重置的新密码
  const pwdForm = reactive({
    newPwd: ""
  });
  const pwdProgress = [
    { color: "#e74242", text: "非常弱" },
    { color: "#EFBD47", text: "弱" },
    { color: "#ffa500", text: "一般" },
    { color: "#1bbf1b", text: "强" },
    { color: "#008000", text: "非常强" }
  ];
  // 当前密码强度（0-4）
  const curScore = ref();
  const roleOptions = ref([]);
  function handleUpdate(row) {
    console.log(row);
  }

  const handleDelete = async row => {
    await delUser(row.id);
    message("删除成功", { type: "success" });
    onSearch();
  };

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    form.pageNum = val;
    onSearch();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }

  const loadAllUser = async () => {
    let params = {
      pageNum: 1,
      pageSize: 500
    };
    let { data } = await getUserList(params);
    allUserList.value = data.records || [];
  };

  async function onSearch() {
    loading.value = true;
    const { data } = await getUserList(toRaw(form));
    dataList.value = data.records || [];
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?) {
    addDialog({
      title: `${title}教师`,
      props: {
        id: row?.id ?? undefined
      },
      width: "1000px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(AddUpTeacher, { ref: formRef, formInline: null }),
      beforeSure: done => {
        const FormRef = formRef.value.getRef();
        const formVal = formRef.value.getFormVal();
        console.log("formVal", formVal);
        function chores() {
          message("操作成功", {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
          loadAllUser();
        }
        FormRef.validate(async valid => {
          if (valid) {
            let newData = { ...formVal };
            console.log("newData ", newData);
            // 表单规则校验通过
            if (title === "新增") {
              await addUser(newData);
              chores();
            } else {
              delete newData.password;
              await upUser(newData);
              chores();
            }
          }
        });
      }
    });
  }

  // 积分调整
  const scoreRef = ref();
  function changeScore() {
    addDialog({
      title: "积分调整",
      props: {
        userList: allUserList.value || []
      },
      width: "500px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(EditScore, { ref: scoreRef, formInline: null }),
      beforeSure: done => {
        const FormRef = scoreRef.value.getRef();
        const formVal = scoreRef.value.getFormVal();
        function chores() {
          message("操作成功", {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("formVal ", formVal);
            if (formVal.targetUserId == formVal.originUserId) {
              return message("'被给与对象'不能是'给予对象'", {
                type: "warning"
              });
            }
            // 表单规则校验通过
            await doChangeScore(formVal);
            chores();
          }
        });
      }
    });
  }

  watch(
    pwdForm,
    ({ newPwd }) =>
      (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score)
  );

  /** 重置密码 */
  function handleReset(row) {
    pwdForm.newPwd = "123456";
    addDialog({
      title: `重置 '${row.name}' 用户的密码`,
      width: "500px",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <>
          <ElForm ref={ruleFormRef} model={pwdForm}>
            <ElFormItem
              prop="newPwd"
              rules={[
                {
                  required: true,
                  validator: (rule, value, callback) => {
                    if (value === "") {
                      callback(new Error("请输入新密码"));
                    } else if (value.length < 6) {
                      callback(new Error("密码长度不可小于6位"));
                    } else {
                      callback();
                    }
                  },
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={pwdForm.newPwd}
                placeholder="请输入新密码"
              />
            </ElFormItem>
          </ElForm>
          <div class="mt-4 flex mb-[16px]">
            {pwdProgress.map(({ color, text }, idx) => (
              <div
                class="w-[19vw]"
                style={{ marginLeft: idx !== 0 ? "4px" : 0 }}
              >
                <ElProgress
                  striped
                  striped-flow
                  duration={curScore.value === idx ? 6 : 0}
                  percentage={curScore.value >= idx ? 100 : 0}
                  color={color}
                  stroke-width={10}
                  show-text={false}
                />
                <p
                  class="text-center"
                  style={{ color: curScore.value === idx ? color : "" }}
                >
                  {text}
                </p>
              </div>
            ))}
          </div>
        </>
      ),
      closeCallBack: () => (pwdForm.newPwd = ""),
      beforeSure: done => {
        ruleFormRef.value.validate(async valid => {
          if (valid) {
            // 根据实际业务使用pwdForm.newPwd和row里的某些字段去调用重置用户密码接口即可
            await resetPwd({ id: row.id, password: pwdForm.newPwd });

            // 表单规则校验通过
            message(`已成功重置' ${row.name} '的密码`, {
              type: "success"
            });
            done(); // 关闭弹框
            // onSearch(); // 刷新表格数据
          }
        });
      }
    });
  }

  onMounted(async () => {
    onSearch();

    // 角色列表
    let params = {
      pageNum: 1,
      pageSize: 500
    };
    const { data } = await getRoleList(params);
    roleOptions.value = handleTree(data.records || []);

    // 获取所有用户
    loadAllUser();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    treeData,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    changeScore,
    handleUpdate,
    handleDelete,
    handleReset,
    handleSizeChange,
    handleCurrentChange
  };
}
